package controller;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Vector;
import java.util.regex.Pattern;

import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;

import dal.JMLDatabase;
import dal.datastore.Table;
import dal.datastore.TableData;
import dto.ColumnDTO;
import dto.ConditionStatementDTO;
import dto.RowDTO;

public class FROMCommand {
	private String _command;
	private String _database;
	private JMLDatabase _dao;

	/**
	 * Constructor
	 * 
	 * @param _command
	 * @throws Exception
	 */
	public FROMCommand(String _command) throws Exception {
		super();
		if (ControllerConfiguration.DEFAULT_DATABASE.isEmpty()) {
			throw new Exception("The default dabase is not set");
		}
		this._database = ControllerConfiguration.DEFAULT_DATABASE;
		this._dao = new JMLDatabase();
		this._command = _command;
	}

	public String getCommand() {
		return _command;
	}

	public void setCommand(String _command) {
		this._command = _command;
	}

	/**
	 * Execute from command
	 * 
	 * @return TableData
	 * @throws Exception 
	 */
	public TableData excute() throws Exception {
		if (isFromCommand()) {
			ArrayList<String> elements = parseFromCommand();

			TableData temp = new TableData("temp");
			
			if (elements.size() == 3) {
				TableData tbl1 = _dao.getTableData(_database, elements.get(0));
				TableData tbl2 = _dao.getTableData(_database, elements.get(1));
				
				String join = elements.get(2);
				
				return tbl1.join(tbl2, join);
			} else {
				for (String string : elements) {
					TableData tbl = _dao.getTableData(_database, string);
					temp = temp.DescartesMultiply(tbl);
				}
				return temp;
			}
		}
		return null;
	}

	/**
	 * Parse from command into elements
	 * 
	 * @return ArrayList<String>
	 */
	private ArrayList<String> parseFromCommand() {
		// ArrayList<String> elements = new ArrayList<>();
		Pattern p = Pattern.compile("(join|left join|right join|(\\s+on\\s+)|,)", Pattern.CASE_INSENSITIVE);
		String[] strings = p.split(_command);
		return QueryParser.removeAllEmptyString(strings);
	}

	private boolean isFromCommand() {
		String operators = "(=|!=|>|<|<=|>=|like|not like)";
		
		String joins = "(\\w+)\\s+(?i)(join|left join|right join)\\s+(\\w+)\\s+on\\s+(\\w+.\\w+)\\s*"
				+ operators + "\\s*\\w+.\\w+";

		String from = "((\\w+)(\\s*,\\s*\\w+)*|" + joins + ")";
		return _command.matches(from);
	}
}
